﻿using System;
using System.Collections.Generic;
using System.Linq;
using ChuanYe.Models;
using ChuanYe.IBLL;
using Microsoft.Practices.Unity;
using ChuanYe.Commom;
using Newtonsoft.Json.Linq;
using System.Web.Http.Cors;

namespace SJPlatForm.Web.Controllers
{
    [EnableCors("*", "*", "*")]
    public class MailController : BaseApiController
    {
        [Dependency]
        public IMailBLL m_bll { get; set; }

        [Dependency]
        public ISms_SendInfoBLL s_bll { get; set; }


        /// <summary>
        /// 消息
        /// </summary>
        [Dependency]
        public IAutomaticBLL automaticBLL { get; set; }

        /// <summary>
        /// 获取全部邮箱用户
        /// </summary>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public List<GetAllMailResult> GetAllMailUsers()
        {
            try
            {
                List<ChuanYe.Models.Model.View_MailUsers> MailUsers = m_bll.GetAllMailUsers();
                List<Departments> AllDepartments = s_bll.GetAllDepartments();
                var result = from d in AllDepartments
                             select new GetAllMailResult
                             {
                                 ID = d.ID,
                                 UserName = d.DepName,
                                 Sort = d.Sort,
                                 children = (from p in MailUsers
                                             where p.DepID == d.ID
                                             select p).OrderByDescending(o=>o.Division).ThenByDescending(o=>o.Sort).ToList()
                             };
                return result.ToList();
            }
            catch (Exception ex)
            { 
                Log.Error("MailController", ex.ToString());
                return new List<GetAllMailResult>();
            }
        }


        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="obj">收件人：Tos 格式：用户ID,用户ID，标题：Title，内容：Brief,附件：InfosCommAttachs 默认:""</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public bool CreateInfosComm(dynamic obj)
        {
            try
            {
                InfosComm Model = new InfosComm();
                Model.Title = obj.Title;
                Model.Brief = obj.Brief;
                
                Model.From = GetLoginInfo(obj.key.ToString()).ID;
                Model.FSState = 0;
                Model.GGState = 0;
                Model.InfosCode = Guid.NewGuid().ToString();
                Model.IsView = false;
                Model.JSState = 0;
                Model.PublishTime = DateTime.Now;
                
                List<UploadDataModel> UploadDataModels = new List<UploadDataModel>();
                if (obj.InfosCommAttachs != null)
                {
                    UploadDataModels = ((JArray)obj.InfosCommAttachs)
                   .Select(x => new UploadDataModel
                   {
                       FileName = (string)x["FileName"],
                       FilePath = (string)x["FilePath"],
                       FileSize = (decimal)x["FileSize"],
                   }).ToList();
                }

                List<InfosCommAttachs> InfosCommAttachsModels = new List<InfosCommAttachs>();
                
                foreach (UploadDataModel UploadModel in UploadDataModels)
                {
                    InfosCommAttachs AttachsModel = new InfosCommAttachs();
                    AttachsModel.FileName = UploadModel.FileName;
                    AttachsModel.FilePath = UploadModel.FilePath;
                    AttachsModel.Title = obj.Title;
                    AttachsModel.FileSize = UploadModel.FileSize;
                    InfosCommAttachsModels.Add(AttachsModel);
                }
                string Tos = obj.Tos;
                string[] ReceiverList = Tos.Split(',');
                bool IsSend = false;
                foreach (var item in ReceiverList)
                {
                    Model.To = Convert.ToInt32(item);
                    IsSend = m_bll.CreateInfosComm(Model, InfosCommAttachsModels);
                }
                if (IsSend)
                {
                    Log.Info(obj.key.ToString(), "发送邮件", "邮件发送成功！");
                }
                return IsSend;
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return false;
            }
        }
        

        /// <summary>
        /// 接收的邮件
        /// </summary>
        /// <param name="obj">是否以接收：IsView 默认：2，页数：page，行数：rows</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public ReceiveMailListResult ReceiveMailGetList(dynamic obj)
        {
            try
            {
                ReceiveMailSearch Search = new ReceiveMailSearch();
                Search.UserID = GetLoginInfo(obj.key.ToString()).ID;
                Search.Keyword = obj.Keyword;
                string IsView = obj.IsView;
                switch (IsView)
                {
                    case "0":
                        Search.IsView= false;
                        break;
                    case "1":
                        Search.IsView = true;
                        break;
                    case "2":
                        Search.IsView = null;
                        break;
                }
                GridPager Pager = new GridPager();
                Pager.page = obj.page;
                Pager.rows = obj.rows;
                return m_bll.ReceiveMailGetList(Search, Pager);
            }
            catch (Exception ex) {
                Log.Error("MailController", ex.ToString());
                return new ReceiveMailListResult();
            }
        }
        /// <summary>
        /// 邮件详情
        /// </summary>
        /// <param name="obj">邮件ID：ID</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public InfosCommInfoResult InfosCommGet(dynamic obj)
        {
            try
            {
                int ID = obj.ID;
                InfosCommInfoResult result = new InfosCommInfoResult();
                result.InfosCommInfo = m_bll.InfosCommGet(ID);
                result.InfosCommAttachsList= m_bll.InfosCommAttachsGet(ID);
                return result;
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return new InfosCommInfoResult();
            }
        }
        /// <summary>
        /// 删除邮件
        /// </summary>
        /// <param name="obj">邮件ID：ID</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public int InfosCommDelete(dynamic obj)
        {
            try
            {
                int ID = obj.ID;
                int result= m_bll.InfosCommDelete(ID);
                if (result > 0)
                {
                    Log.Info(obj.key.ToString(), "发送邮件", "邮件发送成功！");
                }
                return result;
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 批量删除邮件
        /// </summary>
        /// <param name="obj">邮件ID:IDs格式：ID,ID</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public int InfosCommDeleteSome(dynamic obj)
        {
            try
            {
                int result = 0;
                string IDs = obj.IDs;
                string[] IDArr = IDs.Split(',');
                foreach (string ID in IDArr)
                {
                    result= m_bll.InfosCommDelete(Convert.ToInt32(ID));
                }
                if (result > 0) {
                    Log.Info(obj.key.ToString(), "邮件", "邮件删除成功！");
                }
                return result;
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 改变已读状态
        /// </summary>
        /// <param name="obj">邮件ID：ID</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public int InfosCommUpdate(dynamic obj)
        {
            try
            {
                int ID = obj.ID;
                int result= m_bll.InfosCommUpdate(ID);
                if (result > 0)
                {
                    Log.Info(obj.key.ToString(), "邮件", "阅读邮件！");
                }
                return result;
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return -1;
            }
        }

        /// <summary>
        /// 批量 改变已读状态
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public int InfosCommUpdateByIDs(dynamic obj)
        {
            try
            {
                int[] ids = (int[])obj.IDs;
                int result= m_bll.InfosCommUpdateByIDs(ids);
                return result;
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return -1;
            }
        }

        /// <summary>
        /// 公共邮箱列表
        /// </summary>
        /// <param name="obj">是否已读：IsView 默认：2，页数：page，行数：rows</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public PublicMailResult PublicMailGetList(dynamic obj)
        {
            try
            {
                PublicMailSearch Search = new PublicMailSearch();
                Search.UserID = GetLoginInfo(obj.key.ToString()).ID;
                string IsView = obj.IsView;
                Search.Keyword = obj.Keyword;
                switch (IsView)
                {
                    case "0":
                        Search.IsView = false;
                        break;
                    case "1":
                        Search.IsView = true;
                        break;
                    case "2":
                        Search.IsView = null;
                        break;
                }
                GridPager Pager = new GridPager();
                Pager.page = obj.page;
                Pager.rows = obj.rows;
                return m_bll.PublicMailGetList(Search, Pager);
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return new PublicMailResult();
            }
        }
        /// <summary>
        /// 已发邮件列表
        /// </summary>
        /// <param name="obj">是否已读：IsView，页数：page，行数：rows</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public MailSendResult MailSendGetList(dynamic obj)
        {
            try
            {
                MailSendSearch Search = new MailSendSearch();
                Search.UserID = GetLoginInfo(obj.key.ToString()).ID;
                string IsView = obj.IsView;
                Search.Keyword = obj.Keyword;
                switch (IsView)
                {
                    case "0":
                        Search.IsView = false;
                        break;
                    case "1":
                        Search.IsView = true;
                        break;
                    case "2":
                        Search.IsView = null;
                        break;
                }
                GridPager Pager = new GridPager();
                Pager.page = obj.page;
                Pager.rows = obj.rows;
                return m_bll.MailSendGetList(Search, Pager);
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return new MailSendResult();
            }
        }
        /// <summary>
        /// 获取用户接收到的邮件的附件总大小
        /// </summary>
        /// <param name="obj">用户ID：key</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public decimal GetAllInfosCommAttachsSize(dynamic obj)
        {
            try
            {
                int ID = Convert.ToInt32(obj.key);
                return m_bll.GetAllInfosCommAttachsSize(ID);
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 添加日程
        /// </summary>
        /// <param name="obj">日程标题：S_Title，日程内容：S_Cont，行程时间：S_Date，提醒日期：S_TsDate，提醒时间：S_TsTime，提前几天：S_Int</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public int ScheduleCreate(dynamic obj)
        {
            try
            {
                Schedule Model = new Schedule();
                Model.S_Cont = obj.S_Cont;
                Model.S_Date = obj.S_Date; 
                Model.S_Title = obj.S_Title;
                Model.S_TsDate = obj.S_TsDate;
                Model.S_TsTime = obj.S_TsTime;
                Model.S_Int = obj.S_Int;
                Model.S_Rate = 0;
                Model.S_TransUser = GetLoginInfo(obj.key.ToString()).ID;
                Model.S_TransDatetime = DateTime.Now;
                Model.S_Type = "0";
                Model.S_AutomaticState = obj.S_AutomaticState;

                #region 获取客户端IP
                string result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(result))
                {
                    result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                if (string.IsNullOrEmpty(result))
                {
                    result = System.Web.HttpContext.Current.Request.UserHostAddress;
                }
                if (string.IsNullOrEmpty(result))
                {
                    result = "0.0.0.0";
                }
                Model.S_TransIP = result;
                #endregion

                int RT = m_bll.ScheduleCreate(Model);
                var loginInfo=GetLoginInfo(obj.key.ToString());



                //2018/09/20 写入办公消息
                if (Model.S_AutomaticState)
                {
                    Automatic info = new Automatic()
                    {
                        M_SendUserID = loginInfo.ID,
                        M_SendUserName = loginInfo.UserName,
                        M_SendArea = null,
                        M_SendContent = Model.S_Title,
                        M_SendTime = Model.S_Date,
                        M_ReceiveUserID = loginInfo.ID,
                        M_ReceiveUserName = loginInfo.UserName,
                        M_Type = 4,
                        M_IsReplay = 0,
                        M_ReceiveArea = null,
                        M_ReplayTime = obj.M_ReplayTime,
                        M_SendCustomData = RT.ToString(),
                    };
                    automaticBLL.AddAutomatic(info);
                }
                if (RT>0)
                {
                    Log.Info(obj.key.ToString(), "日程", "日程添加成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return -1;
            }
        }
        /// <summary>
        /// 获取日程
        /// </summary>
        /// <param name="obj">日程ID：S_ID</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public Schedule ScheduleGet(dynamic obj)
        {
            try
            {
                int S_ID = Convert.ToInt32(obj.S_ID);
                return m_bll.ScheduleGet(S_ID);
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return new Schedule();
            }
        }
        /// <summary>
        /// 获取某个月的日程信息
        /// </summary>
        /// <param name="obj">时间：Time</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public List<ScheduleGetMonthListResult> ScheduleGetMonthList(dynamic obj)
        {
            try
            {
                ScheduleSearch Search = new ScheduleSearch();
                Search.stateTime = ValueConvert.MonthFristDay(obj.Time);
                Search.endTime = ValueConvert.MonthLastDay(obj.Time);
                Search.UserID = GetLoginInfo(obj.key.ToString()).ID;
                return m_bll.ScheduleGetMonthList(Search);
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return new List<ScheduleGetMonthListResult>();
            }
        }
        /// <summary>
        /// 获取某天的日程信息
        /// </summary>
        /// <param name="obj">时间：Time</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public List<ScheduleGetMonthListResult> ScheduleGetDayList(dynamic obj)
        {
            try
            {
                ScheduleSearch Search = new ScheduleSearch();
                Search.stateTime = ValueConvert.StateTimeConvert(obj.Time);
                Search.endTime = ValueConvert.EndTimeConvert(obj.Time);
                Search.UserID = GetLoginInfo(obj.key.ToString()).ID;
                List<ScheduleGetMonthListResult> result = m_bll.ScheduleGetDayList(Search);
                List<string> temp_CustomeDatas = result.Select(s => s.S_ID.ToString()).ToList();
                var autoList=automaticBLL.GetAutomatic(temp_CustomeDatas);
                foreach (var item in result)
                {
                    var exist = autoList.Where(p => p.M_SendCustomData == item.S_ID.ToString()).FirstOrDefault();
                    item.M_ID = exist != null ? exist.M_ID : 0;
                }
                return result;
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return new List<ScheduleGetMonthListResult>();
            }
        }
        /// <summary>
        /// 修改日程信息
        /// </summary>
        /// <param name="obj">日程ID:S_ID,日程标题：S_Title，日程内容：S_Cont，日程日期：S_Date，提示日期：S_TsDate，提示时间：S_TsTime，提前天数：S_Int</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public int ScheduleUpdate(dynamic obj)
        {
            try
            {
                Schedule model = new Schedule();
                model.S_ID = Convert.ToInt32(obj.S_ID);
                model.S_Title = obj.S_Title;
                model.S_Cont = obj.S_Cont;
                model.S_Date = obj.S_Date;
                model.S_TsDate = obj.S_TsDate;
                model.S_TsTime = obj.S_TsTime;
                model.S_Int = obj.S_Int;
                model.S_AutomaticState = obj.S_AutomaticState;

                //设置消息
                var autoList = automaticBLL.GetAutomatic(new List<string> { model.S_ID.ToString() });
                int isReplay = model.S_AutomaticState == true ? 0: 1;
                if (autoList.Count > 0)
                {
                    automaticBLL.UpdateAutomaticReplay(autoList.FirstOrDefault().M_ID, isReplay);
                }

                int RT = m_bll.ScheduleUpdate(model);
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "日程", "日程修改成功！");
                }
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return -1;
            }
        }

        /// <summary>
        /// 修改日程 消息提醒状态
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public int ScheduleStateUpdate(dynamic obj)
        {
            try
            {
                Schedule model = new Schedule();
                model.S_ID = Convert.ToInt32(obj.S_ID);
                model.S_AutomaticState = obj.S_AutomaticState; //1.设置提醒 0.取消提醒
                //设置消息
                var autoList=automaticBLL.GetAutomatic(new List<string> { model.S_ID.ToString()});
                //取消提醒时，将已存在的消息设置为已读
                int isReplay = model.S_AutomaticState == true ? 0 : 1;
                if (autoList.Count > 0)
                {
                    automaticBLL.UpdateAutomaticReplay(autoList.FirstOrDefault().M_ID, isReplay);
                }
                //设置日程
                int RT = m_bll.ScheduleAutomaticStateUpdate(model);
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return -1;
            }
        }

        /// <summary>
        /// 删除日程信息
        /// </summary>
        /// <param name="obj">日程ID：ID</param>
        /// <returns></returns>
        [System.Web.Http.HttpPost]
        public int ScheduleDelete(dynamic obj)
        {
            try
            {
                int ID = Convert.ToInt32(obj.ID);
                int RT = m_bll.ScheduleDelete(ID);
                if (RT > 0)
                {
                    Log.Info(obj.key.ToString(), "日程", "日程删除成功！");
                }
                //2018/09/20移除消息
                automaticBLL.DeleteAutomatic(ID.ToString());
                return RT;
            }
            catch (Exception ex)
            {
                Log.Error("MailController", ex.ToString());
                return -1;
            }
        }





        public string Options()
        {
            return null; // HTTP 200 response with empty body
        }
    }
}